package com.qzsoft.jeemis.common.typehandle;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;

/**
 * @ClassName JsonObjectHandler
 * @Description json对象转化
 * @author linhuawei
 * @since 2022-01-26
 */
public class JsonObjectHandler extends BaseTypeHandler<JSONObject> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, JSONObject parameter, JdbcType jdbcType)
            throws SQLException {
        ps.setString(i, cover(parameter));
    }

    @Override
    public JSONObject getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return cover(rs.getString(columnName));
    }

    @Override
    public JSONObject getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return cover(rs.getString(columnIndex));
    }

    @Override
    public JSONObject getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return cover(cs.getString(columnIndex));
    }

    private JSONObject cover(String str) {
        JSONObject obj = null;
        if (ObjectUtils.isNotEmpty(str)) {
            try {
                obj = JSON.parseObject(str);
            } catch (Exception e) {
                obj = null;
            }
        }
        return obj;
    }
    
    private String cover(JSONObject obj) {
        if(null == obj) {
            return null;
        }
        return obj.toJSONString();
    }

}
